package com.ocom.emqx.handle;


import com.alibaba.fastjson.JSON;
import com.ocom.common.utils.CommonUtil;
import com.ocom.emqx.config.MqttProperties;
import com.ocom.emqx.service.HnQrCodeMachineService;
import com.ocom.emqx.service.WashingMachineService;
import com.ocom.emqx.vo.HnQrCodePayVo;
import org.bouncycastle.util.encoders.Base64;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

@Component
public class MqttAcceptCallback implements MqttCallbackExtended {

    @Resource
    private HnQrCodeMachineService hnQrCodeMachineService;

    @Resource
    private WashingMachineService washingMachineService ;

    private static final Logger logger = LoggerFactory.getLogger(MqttAcceptCallback.class);

    @Autowired
    private MqttAcceptClient mqttAcceptClient;

    @Autowired
    private MqttProperties mqttProperties;

    /**
     * 客户端断开后触发
     *
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        logger.info("连接断开，可以做重连");
        if (MqttAcceptClient.client == null || !MqttAcceptClient.client.isConnected()) {
            logger.info("emqx重新连接....................................................");
            mqttAcceptClient.reconnection();
        }
    }

    /**
     * 客户端收到消息触发
     *
     * @param topic       主题
     * @param mqttMessage 消息
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        logger.info("接收消息主题 : " + topic);
//        logger.info("接收消息Qos : " + mqttMessage.getQos());
        logger.info("接收消息内容 : " + new String(mqttMessage.getPayload()));


        //扫码盒子
        if(topic.endsWith("pubmsg")){
            String msg = new String(mqttMessage.getPayload());
            try {
                HnQrCodePayVo hnQrCodePayVo =JSON.parseObject(msg, HnQrCodePayVo.class);
                if(hnQrCodePayVo.getCmd().equals("qrcode")){
                    if(CommonUtil.isNull(hnQrCodePayVo.getData())
                    || hnQrCodePayVo.getMoney().equals("0")){
                        return;
                    }
                    byte[] encrypted1 = Base64.decode(hnQrCodePayVo.getData());
                    String tempStr = new String(encrypted1, StandardCharsets.UTF_8);
                    if(tempStr.startsWith("CT")){
                        //建行生活
                        hnQrCodeMachineService.qrPayCard(hnQrCodePayVo);
                    }else{
                        hnQrCodeMachineService.qrCodePay(hnQrCodePayVo);
                    }

                }
            }catch (Exception e){
                logger.info("【mqtt数据解析异常】 message:"+msg);
            }
        }

        //手持扫码盒子
        if(topic.endsWith("pubHandheld")){
            String msg = new String(mqttMessage.getPayload());
            try {
                HnQrCodePayVo hnQrCodePayVo =JSON.parseObject(msg, HnQrCodePayVo.class);
                if(hnQrCodePayVo.getCmd().equals("qrcode")){
                    if(CommonUtil.isNull(hnQrCodePayVo.getData())
                            || hnQrCodePayVo.getMoney().equals("0")){
                        return;
                    }
                    byte[] encrypted1 = Base64.decode(hnQrCodePayVo.getData());
                    String tempStr = new String(encrypted1, StandardCharsets.UTF_8);
                    if(tempStr.startsWith("CT")){
                        //建行生活
                        hnQrCodeMachineService.qrPayCardB(hnQrCodePayVo);
                    }else{
                        hnQrCodeMachineService.qrCodePayB(hnQrCodePayVo);
                    }

                }
            }catch (Exception e){
                logger.info("【mqtt数据解析异常】 message:"+msg);
            }
        }

        //洗衣机
        try {

            String deviceNo = topic.replace("wd/cm/","");

            //洗衣机电吹风 日常心跳
            if (topic.startsWith("wd/cm/")) {
                String msg = new String(mqttMessage.getPayload());
                logger.info(topic + ":" + msg);
                //日常心跳
                if (msg.startsWith("84")) {
                    washingMachineService.updateMachIneStatusWd(deviceNo,msg);
                }
                //一次确认
                if (msg.startsWith("86")) {
                    washingMachineService.comfirmOrder(deviceNo,msg);
                }
                //二次确认
                if (msg.startsWith("87")) {
                    washingMachineService.comfirmOrderTwo(deviceNo,msg);
                }


            }

            //洗衣机电吹风 订单关联 04
            if (topic.startsWith("od/cm/")) {
                String msg = new String(mqttMessage.getPayload());
                logger.info(topic + ":" + msg);
            }

            //设备掉线遗嘱主题
            if (topic.startsWith("os/dis/")) {
                String msg = new String(mqttMessage.getPayload());
                logger.info("设备掉线遗嘱主题:" + topic + ":" + msg);

            }

            //洗设备上传数据主题
            if (topic.startsWith("od/cm/")) {
                String msg = new String(mqttMessage.getPayload());
                logger.info("设备上传数据主题:" + topic + ":" + msg);
                deviceNo = topic.replace("od/cm/","");
                if(msg.startsWith("8A")){
                    washingMachineService.yHMqtt8A(deviceNo,msg);
                }
            }
        } catch (Exception e) {
            logger.error("【mqtt洗衣机处理异常】 err: 【{}】" , e.getMessage());
        }

        return;
    }

    /**
     * 发布消息成功
     *
     * @param token token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        String[] topics = token.getTopics();
        for (String topic : topics) {
            logger.info("向主题：" + topic + "发送消息成功！");
        }
        try {
            MqttMessage message = token.getMessage();
            byte[] payload = message.getPayload();
            String s = new String(payload, "UTF-8");
            logger.info("消息的内容是：" + s);
        } catch (MqttException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接emq服务器后触发
     *
     * @param b
     * @param s
     */
    @Override
    public void connectComplete(boolean b, String s) {
        logger.info("--------------------ClientId:"
                + MqttAcceptClient.client.getClientId() + "客户端连接成功！--------------------");
        // 以/#结尾表示订阅所有以test开头的主题
        // 订阅所有机构主题
//        mqttAcceptClient.subscribe(mqttProperties.getDefaultTopic(), 0);
        mqttAcceptClient.subscribe(mqttProperties.getSubscriptions());
    }
}
